<template>
  <div class="page" ref="pageRef" :class="isMobile() ? 'mobile' : ''">
    <el-container>
      <transition
        v-show="online"
        name="fade-menu"
        enter-active-class="animate__animated animate__fadeInDown  "
        leave-active-class="animate__animated animate__fadeOutUp  "
      >
        <el-header>
          <el-space>
            <div class="query-item">
              <el-checkbox-group v-model="categoryData" size="small">
                <el-checkbox-button label="一般" checked>一般</el-checkbox-button>
                <el-checkbox-button label="动漫" checked>动漫</el-checkbox-button>
                <el-checkbox-button label="人物">人物</el-checkbox-button>
              </el-checkbox-group>
            </div>

            <div class="query-item">
              <el-checkbox-group v-model="purityData" size="small">
                <el-checkbox-button label="SFW" checked>SFW</el-checkbox-button>
                <el-checkbox-button label="Sketchy">Sketchy</el-checkbox-button>
                <el-checkbox-button label="NSFW" v-if="apikey">NSFW</el-checkbox-button>
              </el-checkbox-group>
            </div>
            <div class="query-item">
              <el-dropdown popper-class="resolution-popper">
                <el-button type="primary" size="small">
                  分辨率<i style="margin-left: 8px" class="iconfont icon-unfold"></i>
                </el-button>
                <template #dropdown>
                  <div>
                    <div class="head">
                      <div v-for="item in resolutionData" :key="item.key">
                        {{ item.key }}
                      </div>
                    </div>
                    <div class="content">
                      <el-checkbox-group v-model="currentResolution" size="small">
                        <template v-for="item in resolutionData" :key="item.key">
                          <div>
                            <!-- <el-button v-for="i in item.value" :key="i.key" size="small">
                        {{ i.value }}
                      </el-button> -->
                            <el-checkbox
                              v-for="i in item.value"
                              :key="i.key"
                              :label="i.value"
                              border
                            />
                          </div>
                        </template>
                      </el-checkbox-group>
                    </div>
                  </div>
                </template>
              </el-dropdown>
            </div>
            <div class="query-item">
              <el-dropdown popper-class="resolution-popper">
                <el-button type="primary" size="small">
                  屏幕比例<i style="margin-left: 8px" class="iconfont icon-unfold"></i>
                </el-button>
                <template #dropdown>
                  <div>
                    <div class="head">
                      <div v-for="item in ratioData" :key="item.key">
                        {{ item.key }}
                      </div>
                    </div>
                    <div class="content">
                      <el-checkbox-group v-model="currentRatio" size="small">
                        <template v-for="item in ratioData" :key="item.key">
                          <div>
                            <!-- <el-button v-for="i in item.value" :key="i.key" size="small">
                        {{ i.value }}
                      </el-button> -->
                            <el-checkbox
                              v-for="i in item.value"
                              :key="i.key"
                              :label="i.value"
                              border
                            />
                          </div>
                        </template>
                      </el-checkbox-group>
                    </div>
                  </div>
                </template>
              </el-dropdown>
            </div>
            <div class="query-item">
              <el-dropdown @command="onChangeSort">
                <el-button type="primary" size="small">
                  {{ currentSortItem.key
                  }}<i style="margin-left: 8px" class="iconfont icon-unfold"></i>
                </el-button>

                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      :command="item"
                      v-for="item in sortingData"
                      :key="item.key"
                    >
                      {{ item.key }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown
                @command="
                  (item) => {
                    currentRangeItem = item;
                  }
                "
                v-if="currentSortItem.key == 'Toplist'"
              >
                <el-button type="primary" size="small">
                  {{ currentRangeItem.key
                  }}<i style="margin-left: 8px" class="iconfont icon-unfold"></i>
                </el-button>

                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      :command="item"
                      v-for="item in toplistRangeData"
                      :key="item.key"
                    >
                      {{ item.key }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="query-item">
              <el-button type="" @click="onSearch" size="small">
                <i class="iconfont icon-search"></i> 搜索
              </el-button>
            </div>
          </el-space>
        </el-header>
      </transition>
      <el-main>
        <el-scrollbar>
          <div class="image-wrapper">
            <transition
              v-for="(item, i) in items"
              v-show="!switchLoading"
              :key="i"
              class="image-box"
              name="fade-menu"
              enter-active-class="animate__animated animate__zoomIn  "
              leave-active-class="animate__animated animate__zoomOut  "
            >
              <div @contextmenu.prevent.stop="openMenu($event, item)">
                <el-image
                  :src="item.cover"
                  :lazy="false"
                  fit="cover"
                  :initial-index="i"
                  :preview-src-list="[item.isLocal ? item.cover : item.image]"
                />
                <div class="title">{{ item.title }}</div>
              </div>
            </transition>
          </div>
        </el-scrollbar>
      </el-main>

      <el-footer>
        <div class="footer-wrapper">
          <div class="switch-wrapper">
            <el-switch
              v-model="online"
              inline-prompt
              active-text="在线"
              inactive-text="本地"
              :loading="switchLoading"
              :before-change="beforeChangeOnline"
            />
          </div>
          <transition
            v-show="online"
            name="fade-menu"
            enter-active-class="animate__animated animate__fadeInUp "
            leave-active-class="animate__animated animate__fadeOutDown"
          >
            <div class="pagination-wrapper">
              <el-pagination
                layout="prev, pager, next"
                :page-size="24"
                :page-count="result.totalPage"
                @current-change="onPageChange"
              />
            </div>
          </transition>
        </div>
      </el-footer>
    </el-container>

    <transition name="fade-menu">
      <div
        v-show="rightMenu.show"
        :style="{ left: rightMenu.left + 'px', top: rightMenu.top + 'px' }"
        class="contextmenu"
      >
        <div @click="onDownload">下载</div>
        <div @click="onSetTheWallpaper">设置壁纸</div>
        <div v-if="rightMenu.item.isLocal" @click="onDeleteWallpaper">删除</div>
        <hr />
        <div @click="onDownloadLocal">下载到本地</div>
        <hr />
        <div @click="rightMenu.show = false">关闭</div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import wallHavenService from "@/api-services/apis/wallhaven";
import nasFileService from "@/api-services/apis/nasFile";
import { SearchRequest, SearchResult } from "@/api-services/models";
import { ElMessage } from "element-plus";
import bus from "vue3-eventbus";
import eventKey from "@/const/busEventConstKey";
import { isMobile } from "@/utils/common";
// import { storeToRefs } from "pinia";
import { useCommonStore } from "@/store/modules/common";
import constSettingKey from "@/const/constSettingKey";
import { SearchResultItemExt } from "@/api-services/models/extension/extension";
// import { FileInfo } from "@/api-services/models/extension/extension";
const pageRef = ref<any>(null);
const request = ref<SearchRequest>({});
const result = ref<SearchResult>({});
const items = ref<SearchResultItemExt[] | null>();
// const previewList = ref<string[] | undefined>([]);
const categoryData = ref<string[]>(["一般", "动漫"]);
const purityData = ref<string[]>(["SFW"]);
const online = ref(true);
const switchLoading = ref(false);
const sortingData = ref([
  {
    key: "Relevance",
    value: "relevance",
  },
  {
    key: "Random",
    value: "random",
  },
  {
    key: "Date Added",
    value: "date_added",
  },
  {
    key: "Views",
    value: "views",
  },
  {
    key: "Favorites",
    value: "favorites",
  },
  {
    key: "Toplist",
    value: "toplist",
  },
  {
    key: "Hot",
    value: "hot",
  },
]);

const toplistRangeData = ref([
  {
    key: "Last Day",
    value: "1d",
  },
  {
    key: "Last Three Days",
    value: "3d",
  },
  {
    key: "Last Week",
    value: "1w",
  },
  {
    key: "Last Month",
    value: "1M",
  },
  {
    key: "Last 3 Months",
    value: "3M",
  },
  {
    key: "Last 6 Months",
    value: "6M",
  },
  {
    key: "Last Year",
    value: "1y",
  },
]);

const resolutionData = ref([
  {
    key: "Ultrawide",
    value: [
      {
        key: "2560 × 1080",
        value: "2560x1080",
      },
      {
        key: "3440 × 1440",
        value: "3440x1440",
      },
      {
        key: "3840 × 1600",
        value: "3840x1600",
      },
    ],
  },
  {
    key: "16:9",
    value: [
      {
        key: "1280 × 720",
        value: "1280x720",
      },
      {
        key: "1600 × 900",
        value: "1600x900",
      },
      {
        key: "1920 × 1080",
        value: "1920x1080",
      },
      {
        key: "2560 × 1440",
        value: "2560x1440",
      },
      {
        key: "3840 × 2160",
        value: "3840x2160",
      },
    ],
  },
  {
    key: "16:10",
    value: [
      {
        key: "1280 × 800",
        value: "1280x800",
      },
      {
        key: "1600 × 1000",
        value: "1600x1000",
      },
      {
        key: "1920 × 1200",
        value: "1920x1200",
      },
      {
        key: "2560 × 1600",
        value: "2560x1600",
      },
      {
        key: "3840 × 2400",
        value: "3840x2400",
      },
    ],
  },
  {
    key: "4:3",
    value: [
      {
        key: "1280 × 960",
        value: "1280x960",
      },
      {
        key: "1600 × 1200",
        value: "1600x1200",
      },
      {
        key: "1920 × 1440",
        value: "1920x1440",
      },
      {
        key: "2560 × 1920",
        value: "2560x1920",
      },
      {
        key: "3840 × 2880",
        value: "3840x2880",
      },
    ],
  },
  {
    key: "5:4",
    value: [
      {
        key: "1280 × 1024",
        value: "1280x1024",
      },
      {
        key: "1600 × 1280",
        value: "1600x1280",
      },
      {
        key: "1920 × 1536",
        value: "1920x1536",
      },
      {
        key: "2560 × 2048",
        value: "2560x2048",
      },
      {
        key: "3840 × 3072",
        value: "3840x3072",
      },
    ],
  },
]);

const ratioData = ref([
  {
    key: "Wide",
    value: [
      {
        key: "16 × 9",
        value: "16x9",
      },
      {
        key: "16 × 10",
        value: "16x10",
      },
    ],
  },
  {
    key: "Ultrawide",
    value: [
      {
        key: "21 × 9",
        value: "21x9",
      },
      {
        key: "32 × 9",
        value: "32x9",
      },
      {
        key: "48 × 9",
        value: "48x9",
      },
    ],
  },
  {
    key: "Portrait",
    value: [
      {
        key: "9 × 16",
        value: "9x16",
      },
      {
        key: "10 × 16",
        value: "10x16",
      },
      {
        key: "9 × 18",
        value: "9x18",
      },
    ],
  },
  {
    key: "Square",
    value: [
      {
        key: "1 × 1",
        value: "1x1",
      },
      {
        key: "3 × 2",
        value: "3x2",
      },
      {
        key: "4 × 3",
        value: "4x3",
      },
      {
        key: "5 × 4",
        value: "5x4",
      },
    ],
  },
]);
const commonStore = useCommonStore();
// const { allSetting } = storeToRefs(commonStore);
const { getSettingValue } = commonStore;
const currentResolution = ref([]);
const currentRatio = ref([]);
const currentSortItem = ref(sortingData.value[0]);
const currentRangeItem = ref(sortingData.value[0]);
const apikey = ref(getSettingValue(constSettingKey.壁纸ApiKey));
// const localFiles = ref<FileInfo[] | undefined | null>([]);
const rightMenu = ref({
  show: false,
  left: 0,
  top: 0,
  item: <SearchResultItemExt>{},
});
async function loadLocalWallpaper() {
  let _set = getSettingValue(constSettingKey.壁纸存储目录);
  if (!_set) {
    ElMessage({
      message: "请先设置壁纸目录",
      type: "error",
    });
    return false;
  }
  switchLoading.value = true;
  let result = await nasFileService.GetDirectoryContents({
    path: _set,
  });
  items.value = result.fileInfos
    ?.filter((x) => !x.isDirectory)
    .map((x) => {
      return {
        cover: nasFileService.FileLink(x.physicalPath),
        image: x.physicalPath,
        title: x.name,
        name: x.name,
        isLocal: true,
      };
    });
  switchLoading.value = false;
  return true;
}
async function search() {
  hideMenu();
  switchLoading.value = true;
  result.value = await wallHavenService.Search(request.value);
  items.value = result.value.items as SearchResultItemExt[];

  switchLoading.value = false;
  // previewList.value = items.value?.map((x) => x.image || "");
}

function onSearch() {
  console.log(currentResolution.value);

  request.value.categories = `${handleConvertParam(
    categoryData.value,
    "一般"
  )}${handleConvertParam(categoryData.value, "动漫")}${handleConvertParam(
    categoryData.value,
    "人物"
  )}`;
  request.value.purity = `${handleConvertParam(
    purityData.value,
    "SFW"
  )}${handleConvertParam(purityData.value, "Sketchy")}${handleConvertParam(
    purityData.value,
    "NSFW"
  )}`;
  request.value.sorting = currentSortItem.value.value;
  if (currentSortItem.value.key == "Toplist") {
    request.value.topRange = currentRangeItem.value.value;
  }
  request.value.resolutions =
    currentResolution.value?.length > 0 ? currentResolution.value.join(",") : "";
  request.value.ratios =
    currentRatio.value?.length > 0 ? currentRatio.value.join(",") : "";
  if (apikey.value) {
    request.value.apiKey = apikey.value;
  }
  search();
}

function handleConvertParam(array, key) {
  return array && array.filter((x) => x == key).length > 0 ? 1 : 0;
}

function onPageChange(page) {
  request.value.page = page;
  onSearch();
}
function onChangeSort(item) {
  currentSortItem.value = item;
  if (item.key == "Toplist") {
    currentRangeItem.value = toplistRangeData.value[3];
  }
}

async function onDownload() {
  hideMenu();
  let path = rightMenu.value.item.isLocal
    ? rightMenu.value.item.image
    : await wallHavenService.Download(rightMenu.value.item.image || "");
  ElMessage({
    type: "success",
    message: "壁纸下载成功",
  });
  return path;
}

async function onDownloadLocal() {
  hideMenu();
  await nasFileService.FileDownload(
    rightMenu.value.item.image,
    rightMenu.value.item.name,
    rightMenu.value.item.isLocal
  );
}
async function onSetTheWallpaper() {
  let path = await onDownload();
  console.log(path);
  bus.emit(eventKey.changeWallpaper, path);
}

function hideMenu() {
  rightMenu.value.show = false;
}

function openMenu(e, item?) {
  const menuMinWidth = 100;
  if (pageRef.value == null) return;
  const offsetLeft = pageRef.value.getBoundingClientRect().left; // container margin left
  const offsetTop = pageRef.value.getBoundingClientRect().top; // container margin left

  const offsetWidth = pageRef.value.offsetWidth; // container width
  const maxLeft = offsetWidth - menuMinWidth; // left boundary
  const left = e.clientX - offsetLeft; // margin right

  if (left > maxLeft) {
    rightMenu.value.left = maxLeft;
  } else {
    rightMenu.value.left = left;
  }

  rightMenu.value.top = e.clientY - offsetTop + 36;
  rightMenu.value.item = item;
  rightMenu.value.show = true;
}

async function beforeChangeOnline() {
  // switchLoading.value = true;
  let flag = true;
  if (online.value) {
    flag = await loadLocalWallpaper();
  } else {
    await search();
  }
  // switchLoading.value = false;
  return flag;
  // return new Promise((resolve) => {
  //   setTimeout(() => {
  //     switchLoading.value = false;
  //     return resolve(true);
  //   }, 1000);
  // });
}

async function onDeleteWallpaper() {
  await nasFileService.DeleteDirectoryContent({
    path: rightMenu.value.item.image,
    isDirectory: false,
  });
  hideMenu();
  loadLocalWallpaper();
}
search();
</script>

<style lang="scss" scoped>
.page {
  ::v-deep(.el-main) {
    padding: 0;
  }
  ::v-deep(.el-footer) {
    height: initial;
    text-align: center;
    .pagination-wrapper {
      display: inline-flex;
      flex: 1;
      justify-content: center;
    }
    .el-pager li {
      background: initial;
    }
    .el-pagination button {
      background: initial;
    }
  }
  ::v-deep(.el-header) {
    padding: 0px 10px 0 10px;
    height: initial;
  }
  ::v-deep(.el-space) {
    flex-wrap: wrap;
  }
  ::v-deep(.el-container) {
    height: 100%;
  }
  ::v-deep(.el-scrollbar) {
    width: 100%;
    height: 100%;
  }
  ::v-deep(.el-switch__core) {
    width: 60px;
  }
  .image-wrapper::after {
    content: "";
    width: 100px;
  }
  .image-wrapper {
    display: flex;
    flex-flow: wrap;
    align-content: space-between;
    justify-content: space-between;
    width: 100%;
    padding: 10px 10px 0 10px;
    box-sizing: border-box;
    .image-box {
      flex: 1;
      text-align: center;
      padding: 0px 0 10px 0;
      ::v-deep(.el-image) {
        border-radius: 4px;
      }
      ::v-deep(img.el-image__inner) {
        width: 150px;
        height: 100px;
      }
      .title {
        text-align: center;
        font-size: 0.8rem;
      }
    }
  }

  .footer-wrapper {
    display: flex;
    height: 36px;
  }
  .switch-wrapper {
    width: 60px;
  }
}
.mobile {
  .footer-wrapper {
    display: block;
    height: initial;
    .switch-wrapper {
      width: 100%;
    }
  }
}
.query-item {
  margin-top: 10px;
}
.contextmenu {
  position: absolute;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 5px;
  box-shadow: 0px 0px 10px rgb(0 0 0 / 30%);
  color: #333;
  font-size: 14px;
  text-align: left;
  width: 100px;
  overflow: hidden;
  padding: 2px 0px;
  text-shadow: none;
  z-index: 100;
  hr {
    border: none;
    border-top: 1px solid #ddd;
  }
  div {
    cursor: pointer;
    font-size: 13px !important;
    color: #333;
    border-radius: 5px;
    line-height: 2;
    padding: 0px 12px;
    display: flex;
    align-items: center;
    margin: 3px 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  div:hover {
    background: #4b9efb;
    color: white;
    border-radius: 5px;
  }
}
</style>

<style lang="scss">
.resolution-popper {
  color: #333;
  .el-scrollbar {
    width: 400px;
  }
  .head {
    display: flex;
    div {
      flex: 1;
      text-align: center;
      padding: 10px;
    }
  }
  .content {
    > div {
      display: flex;
    }
    > div > div {
      flex: 1;
      text-align: center;
      button {
        font-size: 0.7rem;
        width: 78px;
        margin-bottom: 2px;
      }
      .el-button + .el-button {
        margin-left: 0px;
      }
      .el-checkbox {
        font-size: 0.7rem;
        width: 78px;
        margin-bottom: 2px;
        margin-right: 0;
        padding: 0;
        .el-checkbox__input {
          display: none;
        }
        .el-checkbox__label {
          padding: 0;
          text-align: center;
          display: block;
          width: 100%;
        }
      }
    }
  }
}
</style>
